package com.example.lay.io;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * Created by Lay on 2014/12/8.
 */
public class MyFileActivity extends Activity {
    private final static String FILE_NAME = "wscl.bin";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_file);
        ((Button) findViewById(R.id.btnWriteFile)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = ((EditText) findViewById(R.id.eTxtWrite)).getText().toString();
                PrintStream out = null;
                try {
                    FileOutputStream fs = openFileOutput(FILE_NAME, MODE_APPEND);
                    out = new PrintStream(fs);
                    out.print(content);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    out.close();
                }

            }
        });
        ((Button) findViewById(R.id.btnReadFile)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileInputStream fis = null;
                try {
                    fis = openFileInput(FILE_NAME);
                    byte[] buf = new byte[1024];
                    StringBuffer content = new StringBuffer();
                    int len = 0;
                    while ((len = fis.read(buf)) > 0) {
                        content.append(new String(buf, 0, len));
                    }
                    ((EditText)findViewById(R.id.eTxtRead)).setText(content);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fis.close();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
